// import './assets/main.css'

import { createApp } from 'vue'
// import { createPinia } from 'pinia'
// import { autoupdate } from './auto-update'

import App from './App.vue'
import router from './router'
import store from './stores'

const app = createApp(App)

// app.use(createPinia())
app.use(router)
app.use(store)
app.mount('#app')

// let lastSrcs

// const scriptReg = /\<script.*src=["'](?<src>[^"']+)/gm

// // 获取最新script链接
// async function extractNewScripts() {
//   const html = await fetch('/?_timestamp=' + Date.now()).then((resp) => resp.text())
//   scriptReg.lastIndex = 0
//   let result = []
//   let match
//   while ((match = scriptReg.exec(html))) {
//     result.push(match.groups.src)
//   }
//   return result
// }

// async function needUpdate() {
//   const newScript = await extractNewScripts()
//   if (!lastSrcs) {
//     lastSrcs = newScript
//     return false
//   }
//   let result = false
//   if (lastSrcs.length !== newScript.length) {
//     result = true
//   }
//   for (let i = 0; i < lastSrcs.length; i++) {
//     if (lastSrcs[i] !== newScript[i]) {
//       result = true
//       break
//     }
//   }
//   lastSrcs = newScript
//   return result
// }

// const DURATION = 2000
// function autoRefresh() {
//   setTimeout(async () => {
//     const willUpdate = await needUpdate()
//     if (willUpdate) {
//       const result = confirm('页面有更新，点击确定刷新页面。')
//       if (result) {
//         location.reload()
//       }
//     }
//     autoRefresh()
//   }, DURATION)
// }

let lastSrcs

const scriptReg = /<script[^>]*src=(["'])(?<src>[^\1]+?)\1/g

// 获取最新 script 链接
async function extractNewScripts() {
  try {
    const html = await fetch('/?_timestamp=' + Date.now()).then((resp) => {
      if (!resp.ok) {
        throw new Error(`HTTP error! status: ${resp.status}`)
      }
      return resp.text()
    })
    scriptReg.lastIndex = 0
    let result = []
    let match
    while ((match = scriptReg.exec(html))) {
      result.push(match.groups.src)
    }
    return result
  } catch (error) {
    console.error('Failed to fetch HTML:', error)
    return []
  }
}

async function needUpdate() {
  const newScript = await extractNewScripts()
  if (!lastSrcs || lastSrcs.length === 0) {
    lastSrcs = newScript
    return false
  }
  let result = false
  if (lastSrcs.length !== newScript.length) {
    result = true
  }
  for (let i = 0; i < lastSrcs.length; i++) {
    if (lastSrcs[i] !== newScript[i]) {
      result = true
      break
    }
  }
  lastSrcs = newScript
  return result
}

const DURATION = 2000
function autoRefresh() {
  setInterval(async () => {
    const willUpdate = await needUpdate()
    if (willUpdate) {
      const result = confirm('页面有更新，点击确定刷新页面。')
      if (result) {
        location.reload()
      }
    }
  }, DURATION)
}

autoRefresh()

// export default autoRefresh
